Leetcode-Valid Anagram

Valid Anagram

给定两个字符串,判断其中一个字符串是否是另一个字符串的异序组合。
Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.

Description

tip:anagram的意思是把单词的字母顺序打乱,重新排列后变成一个新单词。

解题思路1
将两个字符串排序后直接比较是否相同。

1
2
3
4
5
6
7
8
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return sorted(s) == sorted(t)

解题思路2
采用字典的方式,分别记录两个字符串中每个字符的出现次数,比较字典是否相同。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict1, dict2 = {}, {}
for i in s:
dict1[i] = dict1.get(i, 0) + 1
for j in t:
dict2[j] = dict2.get(j, 0) + 1
return dict1 == dict2

tip:
dict.get(key, default=None):对于键key返回其对应的值,或者若dict中不包含key则返回default(注意,default的默认值是None)。